const BaseUrl = 'http://127.0.0.1:8899'; // 这里判断开发环境生产环境

const GetParams = data => {
  let arr = [];
  Object.keys(data).forEach(key => {
    arr.push(`${key}=${encodeURI(data[key])}`);
  });
  return arr.join('&');
};

export const Request = (method = 'get', url = '', data = null, config = {}) => {
  const isGet = /get/i.test(method);
  const {
    headers = isGet ? {} : {'Content-Type': 'application/json;charset=utf-8'},
    baseUrl = '',
    timeout = 2000, // 设置延时
    resType = 'json', // 这里是设置返回数据的格式 目前支持 json、text、blob、formData、arrayBuffer
  } = config; //这里就是config参数的格式内容
  return new Promise((resolve, reject) => {
    let timer = null;
    timer = setTimeout(() => {
      const tip = `接口${url}超时`;
      console.error(tip);
      reject(tip);
    }, timeout);
    let sufixUrl = isGet && !!data ? `?${GetParams(data)}` : '';
    let theUrl = `${!!baseUrl ? baseUrl : BaseUrl}${url}${sufixUrl}`;
    fetch(theUrl, {method, headers, body: isGet ? null : JSON.stringify(data)})
      .then(res => res[resType]())
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        console.error(`接口${url}fetch出错:${err}`);
        reject(err);
      })
      .finally(() => {
        clearTimeout(timer); // 终止计算超时
        timer = null; // 释放内存
      });
  });
};
